﻿using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Data;
using System.Web.Security;

namespace SPCIT.WebParts
{
    [Guid("5e785433-1e1c-483d-a2cc-16c2d00e3237")]
    public class ManageUsers : System.Web.UI.WebControls.WebParts.WebPart
    {
        private DataGrid dg;

        public ManageUsers()
        {
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (!this.Page.IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            SPWeb webContext = SPControl.GetContextWeb(Context);
            if (webContext.CurrentUser.IsSiteAdmin)
            {
                if (Membership.Provider != null)
                {
                    int totalUsers;
                    //Get users
                    MembershipUserCollection users = Membership.Provider.GetAllUsers(0, 1000, out totalUsers);

                    //Create table
                    DataTable dt = new DataTable();
                    dt.Columns.Add(new DataColumn("Username", typeof(string)));
                    dt.Columns.Add(new DataColumn("Email", typeof(string)));

                    //Add each user to the table
                    foreach (MembershipUser user in users)
                    {
                        DataRow row = dt.NewRow();
                        row[0] = user.UserName;
                        row[1] = user.Email;

                        dt.Rows.Add(row);
                    }

                    //Create DataView
                    DataView dataView = new DataView(dt);
                    dataView.AllowDelete = true;
                    dataView.AllowEdit = true;

                    //Bind data to DataGrid
                    dg.DataSource = dataView;
                    dg.DataBind();
                }
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            dg = new DataGrid();

            //Data columns
            dg.Columns.Add(new BoundColumn() { HeaderText = "Username", DataField = "Username", ReadOnly = true });
            dg.Columns.Add(new BoundColumn() { HeaderText = "Email", DataField = "Email" });

            //Command columns
            dg.Columns.Add(new EditCommandColumn() { CancelText = "Annulla", EditText = "Modifica", UpdateText = "Salva", CausesValidation = false });
            dg.Columns.Add(new ButtonColumn() { Text = "Cancella", CommandName = "Delete", CausesValidation = false });

            dg.EditCommand += new DataGridCommandEventHandler(dg_EditCommand);
            dg.UpdateCommand += new DataGridCommandEventHandler(dg_UpdateCommand);
            dg.CancelCommand += new DataGridCommandEventHandler(dg_CancelCommand);
            dg.DeleteCommand += new DataGridCommandEventHandler(dg_DeleteCommand);
            dg.AllowPaging = true;
            dg.AutoGenerateColumns = false;

            this.Controls.Add(dg);
        }

        void dg_CancelCommand(object source, DataGridCommandEventArgs e)
        {
            //Cancel operation
            dg.EditItemIndex = -1;
            BindData();
        }

        void dg_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            //Get user
            MembershipUser user = GetUser(e.Item.Cells[0].Text);

            if (user == null)
                throw new NotSupportedException();

            //Modify email
            user.Email = ((TextBox)e.Item.Cells[1].Controls[0]).Text;

            //Save changes
            Membership.Provider.UpdateUser(user);

            //Exit edit mode on DataGrid item
            dg.EditItemIndex = -1;
            BindData();
        }

        void dg_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            //Delete user
            Membership.Provider.DeleteUser(e.Item.Cells[0].Text, true);

            BindData();
        }

        void dg_EditCommand(object source, DataGridCommandEventArgs e)
        {
            //Enable editing on DataGrid item
            dg.EditItemIndex = e.Item.ItemIndex;
            BindData();
        }

        /// <summary>
        /// Get the user with the specified username
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private MembershipUser GetUser(string username)
        {
            MembershipUser user = null;
            SPWeb webContext = SPControl.GetContextWeb(Context);
            if (webContext.CurrentUser.IsSiteAdmin)
            {
                if (Membership.Provider != null)
                {
                    user = Membership.Provider.GetUser(username, false);
                }
            }
            return user;
        }
    }
}
